import http from '@/utils/http'
import { mockGoodsList, mockGoodsDetail, mockDelay, mockApiResponse } from '@/api/goods/mock'

// 是否使用模拟数据（开发时使用）
const USE_MOCK_DATA = false // 临时启用模拟数据，避免API错误

/**
 * 获取商品列表
 * @param {Object} params - 查询参数
 */
export async function getGoodsList(params = {}) {
  let items = []
  let total = 0
  const { page = 1, pageSize = 10, keyword = '', categoryId = '', include_specs = false } = params
  
  if(USE_MOCK_DATA){
    // 添加模拟延迟，展示加载效果
    await mockDelay(800)
    // 模拟搜索
    let filteredItems = mockGoodsList.items
    if (keyword) {
      filteredItems = filteredItems.filter(item => 
        item.name.toLowerCase().includes(keyword.toLowerCase())
      )
    }
    
    // 模拟分页
    total = filteredItems.length
    const startIndex = (page - 1) * pageSize
    const endIndex = startIndex + pageSize
    items = filteredItems.slice(startIndex, endIndex)
  } else {
    try {
      const result = await http.get('/goods/list', {
        page,
        pageSize,
        keyword,
        categoryId,
        include_specs
      })
      // 安全地访问数据，添加默认值
      if (result && result.data) {
        items = result.data.items || []
        total = result.data.total || 0
      } else if (result && result.items) {
        // 如果数据直接在 result 层级
        items = result.items || []
        total = result.total || 0
      } else {
        // 如果都没有，使用默认值
        items = []
        total = 0
      }
    } catch (error) {
      console.error('获取商品列表失败:', error)
      // API失败时使用模拟数据作为兜底
      let filteredItems = mockGoodsList.items
      if (keyword) {
        filteredItems = filteredItems.filter(item => 
          item.name.toLowerCase().includes(keyword.toLowerCase())
        )
      }
      
      const startIndex = (page - 1) * pageSize
      const endIndex = startIndex + pageSize
      items = filteredItems.slice(startIndex, endIndex)
      total = filteredItems.length
    }
  }
  
  return mockApiResponse({
    items,
    total,
    page: Number(page),
    pageSize: Number(pageSize),
    totalPages: Math.ceil(total / pageSize),
    hasMore: page * pageSize < total
  })
}

/**
 * 获取商品详情
 * @param {string|number} goodsId - 商品ID
 */
export async function getGoodsDetail(goodsId) {
  if(USE_MOCK_DATA){
    await mockDelay(500)
    return mockApiResponse(mockGoodsDetail)
  }
  
  try {
    const result = await http.get(`/goods/detail/${goodsId}`)
    
    if (result && result.data) {
      return mockApiResponse(result.data)
    } else if (result) {
      return mockApiResponse(result)
    } else {
      throw new Error('商品详情数据为空')
    }
  } catch (error) {
    console.error('获取商品详情失败:', error)
    // 降级到模拟数据
    await mockDelay(300)
    return mockApiResponse(mockGoodsDetail)
  }
}

/**
 * 获取商品评价列表
 * @param {string|number} goodsId - 商品ID
 * @param {Object} params - 查询参数
 */
export async function getGoodsEvaluations(goodsId, params = {}) {
  const { page = 1, pageSize = 10 } = params
  
  try {
    const result = await http.get(`/goods/${goodsId}/evaluations`, {
      page,
      pageSize
    })
    
    return {
      list: result.data?.list || result.list || [],
      total: result.data?.total || result.total || 0,
      page: Number(page),
      pageSize: Number(pageSize),
      totalPages: Math.ceil((result.data?.total || result.total || 0) / pageSize)
    }
  } catch (error) {
    console.error('获取商品评价失败:', error)
    return {
      list: [],
      total: 0,
      page: Number(page),
      pageSize: Number(pageSize),
      totalPages: 0
    }
  }
}

/**
 * 添加商品评价
 * @param {string|number} goodsId - 商品ID
 * @param {Object} evaluationData - 评价数据
 */
export async function addGoodsEvaluation(goodsId, evaluationData) {
  try {
    const result = await http.post(`/goods/${goodsId}/evaluations`, evaluationData)
    return result
  } catch (error) {
    console.error('添加商品评价失败:', error)
    throw error
  }
}

/**
 * 获取商品规格
 * @param {string|number} goodsId - 商品ID
 */
export async function getGoodsSpecs(goodsId) {
  try {
    const result = await http.get(`/goods/${goodsId}/specs`)
    return result.data || result || []
  } catch (error) {
    console.error('获取商品规格失败:', error)
    return []
  }
}

/**
 * 获取商品库存
 * @param {string|number} goodsId - 商品ID
 * @param {string|number} specId - 规格ID
 */
export async function getGoodsStock(goodsId, specId) {
  try {
    const result = await http.get(`/goods/${goodsId}/stock`, {
      specId
    })
    return result.data || result || 0
  } catch (error) {
    console.error('获取商品库存失败:', error)
    return 0
  }
}

/**
 * 搜索商品
 * @param {string} keyword - 搜索关键词
 * @param {Object} params - 查询参数
 */
export const searchGoods = async (keyword, params = {}) => {
  try {
    if (!keyword) {
      throw new Error('搜索关键词不能为空')
    }
    
    const result = await http.get('/goods/search', {
      keyword,
      ...params
    })
    
    return {
      items: result.items || result.list || [],
      total: result.total || 0,
      hasMore: result.hasMore || false
    }
  } catch (error) {
    throw error
  }
}

/**
 * 获取热门商品
 * @param {Object} params - 查询参数
 */
export async function getHotGoods(params = {}) {
  const { limit = 10, categoryId = '' } = params
  
  try {
    const result = await http.get('/goods/hot', {
      limit,
      categoryId
    })
    
    return result.data || result || []
  } catch (error) {
    console.error('获取热门商品失败:', error)
    return []
  }
}

/**
 * 获取推荐商品
 * @param {Object} params - 查询参数
 */
export async function getRecommendGoods(params = {}) {
  const { limit = 10, userId = '' } = params
  
  try {
    const result = await http.get('/goods/recommend', {
      limit,
      userId
    })
    
    return result.data || result || []
  } catch (error) {
    console.error('获取推荐商品失败:', error)
    return []
  }
}

/**
 * 获取特价商品
 * @param {Object} params - 查询参数
 */
export async function getSpecialGoods(params = {}) {
  const { limit = 10, discount = 0.8 } = params
  
  try {
    const result = await http.get('/goods/special', {
      limit,
      discount
    })
    
    return result.data || result || []
  } catch (error) {
    console.error('获取特价商品失败:', error)
    return []
  }
}

/**
 * 获取新品商品
 * @param {Object} params - 查询参数
 */
export async function getNewGoods(params = {}) {
  const { limit = 10, days = 30 } = params
  
  try {
    const result = await http.get('/goods/new', {
      limit,
      days
    })
    
    return result.data || result || []
  } catch (error) {
    console.error('获取新品商品失败:', error)
    return []
  }
}

/**
 * 获取商品评论
 * @param {Object} params - 查询参数
 */
export async function getGoodsComments(params) {
  await mockDelay(600)
  if(USE_MOCK_DATA){
   // 模拟评论数据
      const comments = [
        {
          id: 1,
          content: '效果很好，对蚜虫防治效果明显',
          rating: 5,
          user: '农民老李',
          avatar: 'http://gips0.baidu.com/it/u=1690853528,2506870245&fm=3028&app=3028&f=JPEG&fmt=auto?w=1024&h=1024',
          createTime: '2023-12-01',
          images: [
            'http://gips0.baidu.com/it/u=1690853528,2506870245&fm=3028&app=3028&f=JPEG&fmt=auto?w=1024&h=1024',
            'http://gips0.baidu.com/it/u=1690853528,2506870245&fm=3028&app=3028&f=JPEG&fmt=auto?w=1024&h=1024'
          ]
        },
        {
          id: 2,
          content: '价格实惠，发货速度快',
          rating: 4,
          user: '种植户小王',
          avatar: 'http://gips0.baidu.com/it/u=1690853528,2506870245&fm=3028&app=3028&f=JPEG&fmt=auto?w=1024&h=1024',
          createTime: '2023-11-28',
          images: [
            'http://gips0.baidu.com/it/u=1690853528,2506870245&fm=3028&app=3028&f=JPEG&fmt=auto?w=1024&h=1024'
          ]
        }
      ]
      return mockApiResponse({
        items: comments,
        total: comments.length,
        page: 1,
        pageSize: 10,
        totalPages: 1
      })
  }else{
    const result = await http.get('/goods/comments/'+ params.goodsId, {
      page: params.page,
      pageSize: params.pageSize
    })
    return {
      items: result.data.items || result.data.list || [],
      total: result.data.total || 0,
    }
  }
  
}    